Imports Microsoft.VisualBasic
Imports System
Imports System.Web
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Drawing.Drawing2D
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.UI.WebControls
Imports System.Data.SQLite
Imports System.Text.RegularExpressions
Imports CalibreVBDataSetTableAdapters

Public Class LibCalibreVB

    Public Shared Function ExecuteScalar(sql As String) As String
        Try
            Dim connString As String = ConfigurationManager.ConnectionStrings("CalibreDB").ConnectionString
            Using conn As New SQLiteConnection(connString)
                conn.Open()
                Using cmd As New SQLiteCommand(conn)
                    cmd.CommandText = sql
                    cmd.CommandType = CommandType.Text
                    Dim value As Object = cmd.ExecuteScalar()
                    If value IsNot Nothing Then
                        Return value.ToString()
                    Else
                        Return ""
                    End If
                End Using
            End Using
        Catch ex As Exception
            HttpContext.Current.Response.Write(sql)
            HttpContext.Current.Response.End()
        End Try
    End Function

    Public Shared Function GetDataTable(sql_str As String) As DataTable
        Dim connString As String = ConfigurationManager.ConnectionStrings("CalibreDB").ConnectionString
        Dim dataTable As New DataTable()
        Using connection As New SQLiteConnection(connString)
            Using cmd As New SQLiteCommand(sql_str, connection)
                cmd.CommandType = CommandType.Text
                Using adapter As New SQLiteDataAdapter(cmd)
                    adapter.Fill(dataTable)
                End Using
            End Using
        End Using
        Return dataTable
    End Function

    Public Shared Function BuildStartMenu(SiteMapTable As DataTable) As String

        Dim startmenu As New HtmlGenericControl("ul")
        startmenu.Attributes.Add("class", "dropdown-menu")

        Dim expression As String = "[Parent] = 0"
        Dim foundrows() As DataRow
        foundrows = SiteMapTable.Select(expression)

        Dim li As New HtmlGenericControl("li")

        ' Get column 1 & 3 of each returned row. 
        For i = 0 To foundrows.GetUpperBound(0)
            startmenu.Controls.Add(li)
            Dim anchor As New HtmlGenericControl("a")
            If foundrows(i)(1) = "Titles" Then
                anchor.Attributes.Add("href", "/List/titles")
            Else
                anchor.Attributes.Add("href", "/" & foundrows(i)(3))
            End If
            anchor.InnerText = foundrows(i)(1)
            li.Controls.Add(anchor)
        Next i

        Dim lidiv As New HtmlGenericControl("li")
        startmenu.Controls.Add(lidiv)
        lidiv.Attributes.Add("class", "divider")
        Dim lihome As New HtmlGenericControl("li")
        startmenu.Controls.Add(lihome)
        Dim ahome As New HtmlGenericControl("a")
        ahome.Attributes.Add("href", "/")
        ahome.InnerText = "Home"
        lihome.Controls.Add(ahome)

        Dim stringwriter As New System.IO.StringWriter()
        Dim writer As New HtmlTextWriter(stringwriter)
        startmenu.RenderControl(writer)
        Dim videov = New HtmlString(writer.ToString())

        Return stringwriter.ToString()

    End Function

    Public Shared Function GetDescCondensed(ByVal Desc As String, ByVal size As Integer, ByVal id As String, ByVal title As String) As String
        Dim returnValue As String = ""
        If Desc <> "UC" Then
            If Len(Desc) < size Then
                returnValue = Desc
            Else
                returnValue = Left(Desc, size) + "... <a href='/Details/" & id.ToString & "/" & title & "'>Read More</a>"
            End If
        End If
        Return returnValue
    End Function
    Public Shared Function StripAllTags(ByVal html As String) As String
        ' Remove HTML tags.
        Return Regex.Replace(html, "<.*?>", " ")
    End Function

    Public Shared Function StripTags(ByVal html As String) As String
        If Not html = String.Empty Then
            html = Regex.Replace(html, "</?[hH]3[^>]*>", "")
            html = Regex.Replace(html, "</?[div[^>]*>", "")
            html = Regex.Replace(html, "</?[i[^>]*>", "")
            html = Regex.Replace(html, "</?[em[^>]*>", "")
        End If
        Return html
    End Function

    Public Shared Function StripSlug(ByVal str As String) As String
        str = Replace(str, " ", "-")
        str = Replace(str, ":", "")
        str = Replace(str, "+", "")
        str = Replace(str, "& ", "")
        str = Replace(str, "&", "")
        Return str
    End Function

    Public Shared Function CalculateNumberOfPages(totalRows As Integer, pageSize As Integer) As Integer
        Dim result = totalRows Mod pageSize
        If result = 0 Then
            Return totalRows / pageSize
        Else
            Return Int(totalRows / pageSize + 1)
        End If
    End Function

    Public Shared Function GetFormats(ByVal id As Integer) As DataTable
        Dim formatsbybookAdapter As New formatsbybookTableAdapter
        Dim formatsbybookTable As New CalibreVBDataSet.formatsbybookDataTable
        Try
            FormatsbybookTable = FormatsbybookAdapter.GetFormatsByBook(id)
        Catch ex As Exception
            'labelerror.Text = ex.ToString
        End Try
        Return FormatsbybookTable
    End Function

    Public Shared Function GetAuthors(ByVal id As Integer) As DataTable
        Dim authorsbybookAdapter As New authorsbybookTableAdapter
        Dim authorsbybookTable As New CalibreVBDataSet.authorsbybookDataTable
        Try
            authorsbybookTable = authorsbybookAdapter.GetAuthorsByBook(id)
        Catch ex As Exception
            'labelerror.Text = ex.ToString
        End Try
        Return authorsbybookTable
    End Function
    Public Shared Function GetIds(ByVal id As Integer) As DataTable
        Dim idsbybookAdapter As New idsbybookTableAdapter
        Dim idsbybookTable As New CalibreVBDataSet.idsbybookDataTable
        Try
            idsbybookTable = idsbybookAdapter.GetIdsByBook(id)
        Catch ex As Exception
            'labelerror.Text = ex.ToString
        End Try
        Return idsbybookTable
    End Function
    Public Shared Function GetTags(ByVal id As Integer) As DataTable
        Dim tagsbybookAdapter As New tagsbybookTableAdapter
        Dim tagsbybookTable As New CalibreVBDataSet.tagsbybookDataTable
        Try
            tagsbybookTable = tagsbybookAdapter.GetTagsByBook(id)
        Catch ex As Exception
            'labelerror.Text = ex.ToString
        End Try

        Return tagsbybookTable
    End Function
    Public Shared Function GetSeries(ByVal id As Integer) As DataTable
        Dim seriesbybookAdapter As New seriesbybookTableAdapter
        Dim seriesbybookTable As New CalibreVBDataSet.seriesbybookDataTable
        Try
            seriesbybookTable = seriesbybookAdapter.GetSeriesByBook(id)
        Catch ex As Exception
            'labelerror.Text = ex.ToString
        End Try

        Return seriesbybookTable
    End Function
    Public Shared Function GetComments(ByVal id As Integer) As String
        Dim commentsTableAdapter As New CalibreVBDataSetTableAdapters.commentsbybookTableAdapter()
        Dim comments As String = CType(commentsTableAdapter.ScalarGetCommentsByBook(id), String)
        If Not comments = String.Empty Then
            comments = LibCalibreVB.StripAllTags(comments)
            Dim GetTitlebyBook As New CalibreVBDataSetTableAdapters.GetTitlebyBook()
            Dim title As String = StripSlug(CType(GetTitlebyBook.ScalarGetTitlebyBook(id), String))

            comments = LibCalibreVB.GetDescCondensed(comments.ToString, 512, id, title)
            'comments = comments & "</li></ul></ol>"
        End If
        Return comments
    End Function
    Public Shared Function GetRating(ByVal id As Integer) As String

        Dim ratingsTableAdapter As New CalibreVBDataSetTableAdapters.ratingsbybookTableAdapter()
        Dim rating As Object = CType(ratingsTableAdapter.ScalarGetRatingsByBook(id), Object)
        Dim ratingValue As Integer
        If Not (rating Is Nothing) Then
            If Not rating.ToString = String.Empty Then
                ratingValue = CType(rating / 2, String)
            End If

        End If
        Return ratingValue.ToString
    End Function

    Public Shared Function ResizeImageFile(ByVal imageFile() As Byte, ByVal targetSize As Integer) As Object
        Using oldImage As System.Drawing.Image = System.Drawing.Image.FromStream(New MemoryStream(imageFile))
            Dim newSize As Size = CalculateDimensions(oldImage.Size, targetSize)
            Using newImage As Bitmap = New Bitmap(newSize.Width, newSize.Height, PixelFormat.Format24bppRgb)
                Using canvas As Graphics = Graphics.FromImage(newImage)
                    canvas.SmoothingMode = SmoothingMode.AntiAlias
                    canvas.InterpolationMode = InterpolationMode.HighQualityBicubic
                    canvas.PixelOffsetMode = PixelOffsetMode.HighQuality
                    canvas.DrawImage(oldImage, New Rectangle(New Point(0, 0), newSize))
                    Dim m As New MemoryStream
                    newImage.Save(m, ImageFormat.Jpeg)
                    Return m.GetBuffer
                End Using
            End Using
        End Using
    End Function

    Public Shared Function CalculateDimensions(ByVal oldSize As Size, ByVal targetSize As Integer) As Size
        Dim newSize As Size
        If (oldSize.Height > oldSize.Width) Then
            newSize.Width = CType((oldSize.Width * CType((targetSize / CType(oldSize.Height, Single)), Single)), Integer)
            newSize.Height = targetSize
        Else
            newSize.Width = targetSize
            newSize.Height = CType((oldSize.Height * CType((targetSize / CType(oldSize.Width, Single)), Single)), Integer)
        End If
        Return newSize
    End Function

End Class

